package com.itheima.datastructure.stack;

import java.util.Iterator;

/**
 * @author tantao
 * @version 1.0
 * @description: TODO
 * @date 2025/9/15 10:36
 */
public class ArrayStack01<E> implements Stack<E>, Iterable<E> {

    private E[] array;

    private int top; //栈顶索引

    /**
     * 底                顶
     * 0 1 2 3 4 5 6 7 8 9
     * 开始 top==0 ，栈顶元素索引为0
     * 添加元素top移动，top++
     */


    // 构造方法
    public ArrayStack01(int capacity) {
        array = (E[]) new Object[capacity];
    }

    @Override
    public boolean push(E value) {
        if (isFull()) return false;
        array[top] = value;
        top++;
        return true;
    }

    @Override
    public E pop() {
        if (isEmpty()) {
            return null;
        }
//        E e = array[top - 1];
//        top--;
//        return e;
        return array[--top];
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return array[top - 1];
    }

    @Override
    public boolean isEmpty() {
        return top == 0;
    }

    @Override
    public boolean isFull() {
        return top == array.length;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = top;

            @Override
            public boolean hasNext() {
                return p > 0;
            }

            @Override
            public E next() {
                return array[--p];
            }
        };
    }

    static class Node<E> {
        E value;
        Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }
}
